require('dotenv').config()
const axios = require("axios");

const logger = require('../utils/logger')

const tokenModel = require('../models/tokenModel')

class TokenController {
	async accessToken() {
		return (await tokenModel.findOne({_id: process.env.TOKEN_ID})).accessToken
	}

	async setToken(tokens) {
		const res = await tokenModel.updateOne({_id: process.env.TOKEN_ID}, {
			accessToken: tokens.accessToken,
			refreshToken: tokens.refreshToken,
			$inc: {counter: 1}
		})
		logger('Токен был обновлен', 'success')
	}
	async checkToken() {
		try {
			const opts = { headers: { 'Authorization': `Bearer ${await this.accessToken()}` } }
			await axios.get('https://admin.gbee.dev/api/v1/vehicle/', opts)
			return true
		} catch (e) {
			if (e.response.status === 401) {
				return false
			} else {
				logger(e.response, 'error')
			}
		}

	}

	async getNewToken() {
		const url = 'https://admin.gbee.dev/api/v1/login'
		const data = {
			login: process.env.LOGIN,
			password: process.env.PASSWORD
		}
		const opts = { headers: { Authorization: process.env.CLIENT_TOKEN } }

		try {
			const response = await axios.post(url, data, opts)
			await this.setToken(response.data.tokens)
			return response.data.tokens.accessToken
		} catch (e) {
			logger(`Не удалось получить новый токен ${e.response}`, 'error')
		}
	}

	async token() {
		if (await this.checkToken())
			return await this.accessToken()
		else
			return await this.getNewToken()
	}
}

module.exports = new TokenController()